import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { sleep } from "@/utils";
import { useRequest } from "vue-request";

type LoginForm = {
  username: string
  password: string
}

export const userStore = defineStore('userStore', () => {
  const token = ref('')
  const userInfo = ref(null)
  const isLogin = computed(() => !!token.value)

  // 登录
  const login = async (loginForm: LoginForm) => {
    const res = await fetch('/mock/api/user/login', {
      body: JSON.stringify(loginForm),
      method: 'POST'
    }).then((data) => data.json())

    await sleep(1000)
    const { token: newToken, userInfo: newUserInfo } = res
    token.value = newToken
    userInfo.value = newUserInfo
    return res
  }

  // 注销
  const logout = () => {
    token.value = ''
  }

  const getUserInfo = () => {
    return new Promise((resolve, reject) => {
      resolve(userInfo.value)
    })
  }
  return { token, userInfo, isLogin, login }
})
